<template>
  <div>
    <el-upload
      :class="{disabled:fileList.length>0}"
      action="#"
      list-type="picture-card"
      :http-request="upload"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-change="onChange"
      :on-remove="onRemove"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog title="预览" :visible="isShowDialog" @close="isShowDialog=false">
      <img :src="imgurl" alt="">
    </el-dialog>
  </div>
</template>

<script>
const COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
const cos = new COS({
  SecretId: 'AKIDkJcePt63j8HBoAF2YnslbGfpjOnxrWw6',
  SecretKey: 'wc2D8nCLFtIRLzNXR5TbZHjvrXy82h6G'
})
export default {

  data() {
    return {
      imgurl: '',
      isShowDialog: false,
      fileList: [
      ]
    }
  },
  methods: {
    //   上传前校验
    beforeUpload(file) {
      console.log(file)
      // 判断图片格式是否符合
      const type = ['image/png', 'image/jpeg']
      if (!type.includes(file.type)) {
        this.$message.error('目前只支持png,jpeg类型')
        return false
      }
      //   判断图片大小
      const maxSize = 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('图片大小最大为1M')
        return false
      }
    },
    //   真正上传
    upload(params) {
      console.log(60, params.file)
      const { file } = params
      cos.putObject({
        Bucket: 'hr72-1310428994', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: file, // 上传文件对象
        onProgress: function(progressData) {
          // 腾讯云上传进度变化钩子
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        // 上传完成钩子
        console.log(err || data)
        if (!err) {
          // 上传成功
          // console.log(77, data)
          this.$message.success('上传成功')
          // 如果图片只有一张
          /* this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success' */
          // 如果图片有多张
          this.fileList.forEach(img => {
            if (img.uid === file.uid) {
              img.url = 'http://' + data.Location
              img.status = 'success'
            }
          })
        } else {
          this.$message.error('上传失败')
          console.log(err)
        }
      })
    },
    onPreview(file) {
    //   console.log(file)
      this.isShowDialog = true
      this.imgurl = file.url
    },
    onChange(file, newFileList) {
      this.fileList = newFileList
    },
    onRemove(file, newFileList) {
      this.fileList = newFileList
    }
  }
}
</script>

<style lang="scss" >
.disabled{
   .el-upload--picture-card{
       display: none;
   }
}
</style>
